#include "FloraLogger.h"
#include <QApplication>
#include <QTextEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QFileDialog>
#include <QColor>

FloraLogger::FloraLogger() : logToFile(true), showLogWindow(true), logWindowWidget(nullptr)
{
    setupLogFile();
    initLogWindow();
}

FloraLogger::~FloraLogger()
{
    closeLogFile();
}

void FloraLogger::setupLogFile()
{
    QDir logDir(QApplication::applicationDirPath() + "/logs");
    if (!logDir.exists()) {
        logDir.mkpath(".");
    }
    QString filename = QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss") + ".log";
    logFile.setFileName(logDir.filePath(filename));
    if (logFile.open(QIODevice::Append | QIODevice::Text))
    {
        logStream.setDevice(&logFile);
    }
}

void FloraLogger::logMessage(const QString& message, LogLevel level)
{
    QColor color;

    // Set color based on log level
    switch (level) {
    case DEBUG_LOG:
        color = Qt::black;
        break;
    case INFO_LOG:
        color = Qt::blue;
        break;
    case WARN_LOG:
        color = Qt::yellow;
        break;
    case ERROR_LOG:
        color = Qt::red;
        break;
    }

    // Output to console
    qDebug() << message;

    // Write to file if enabled
    if (logToFile && logFile.isOpen())
    {
        logStream << message << endl;
    }

    // Output to log window if enabled
    if (showLogWindow && logView)
    {
        QString htmlMessage = QString("<font color='%1'>%2</font>").arg(color.name()).arg(message);
        emit haveMes(htmlMessage);
        //logView->append(htmlMessage);
    }
}

void FloraLogger::debug(const QString& message)
{
    logMessage(message, DEBUG_LOG);
}

void FloraLogger::info(const QString& message)
{
    logMessage(message, INFO_LOG);
}

void FloraLogger::warn(const QString& message)
{
    logMessage(message, WARN_LOG);
}

void FloraLogger::error(const QString& message)
{
    logMessage(message, ERROR_LOG);
}

void FloraLogger::openLogFile()
{
    if (!logFile.isOpen())
    {
        setupLogFile();
    }
}

void FloraLogger::closeLogFile()
{
    if (logFile.isOpen())
    {
        logFile.close();
    }
}

void FloraLogger::saveLogToFile()
{
    if (logFile.isOpen())
    {
        logFile.flush();
    }
}

void FloraLogger::initLogWindow()
{
    if (!showLogWindow) return;

    logWindowWidget = new QWidget;
    logView = new QTextEdit(logWindowWidget);
    logView->setReadOnly(true);

    // Set the background color to light gray
    logView->setStyleSheet("background-color: rgb(110, 110, 110);"
                           );

    QPushButton *saveButton = new QPushButton("Save Log", logWindowWidget);
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(logView);
    layout->addWidget(saveButton);

    logWindowWidget->setLayout(layout);
    logWindowWidget->hide();

    connect(saveButton, &QPushButton::clicked, this, [this]() {
        QString fileName = QFileDialog::getSaveFileName(logWindowWidget, "Save Log", "", "Text Files (*.txt)");
        if (!fileName.isEmpty())
        {
            QFile file(fileName);
            if (file.open(QIODevice::WriteOnly | QIODevice::Text))
            {
                QTextStream out(&file);
                out << logView->toPlainText();
                file.close();
            }
        }
    });
    connect(this,&FloraLogger::haveMes,logView,&QTextEdit::append,Qt::QueuedConnection);
}

void FloraLogger::embedInWidget(QWidget *parent)
{
    if (!logWindowWidget)
    {
        initLogWindow();
    }
    logWindowWidget->setParent(parent);
    logWindowWidget->show();
}

void FloraLogger::setFont(const QFont& font)
{
    if (logView)
    {
        logView->setFont(font);
    }
}
